/**
 *
 * @version   1.0 2016/7/29
 * @author    黄坚：huangjian@sunmnet.com
 * @since     jdk版本：jdk1.7
 */

var pdm = function () {
	var count = 99999;
	var action = path + '/action/powerdb/designer/';
	//模块新增修改内表单选择器
	var moduleAddOrEditFormSelector = '#moduleAddOrEditForm';

	//数据库表单选择器
	var databaseTableSeletor = '#databaseJqgridTable';
	var databaseAddOrEditFormSelector = '#databaseAddOrEditFormSelector';
	var databaseSearchFormSeletor = '#databaseSearchForm';

	//实体新增弹窗选择器
	var entityAddOrEditFormSelector = '#entityAddOrEditForm';

	//字段新增弹窗选择器
	var addOrEditFieldJqgridTableSelector = '#addOrEditFieldJqgridTable';
	var addFieldFormSelector = '#addFieldForm';

	//版本新增弹窗和内表单选择器
	var versionAddFormSelector = '#addVersionForm';

	//新增关系模块
	var relAddOrEditModelFormSelector = '#relAddOrEditModelForm';

	//点击表格的最后行id
	var lastsel;

	/** 枚举关键字定义 */
	var enums = ['pdm_database-databaseCode', 'pdm_field-isNull', 'pdm_field-isPmKey', 'pdm_field-autoIncrement', 'pdm_field-type'];

	/** 获取所有需要翻译的枚举 */
	var enumMap = sPost.getEnumMap(enums);

	/**
	 * 获取当前登录用户的id
	 */
	function getCurAccountId() {
		return accountId;
	}

	/**
	 * 左侧按钮显示/隐藏操作
	 * @param id
	 * @param show
	 */
	function showLeftBtn(id, show) {
		var list = $('.panel-heading').find('button');
		$.each(list, function (key, value) {
			//console.log(key);
			//console.log(value);
			var btnId = $(this).attr('id');
			//console.log(btnId);
			if (btnId == id) {
				show ? $(this).show() : $(this).hide();
			} else {
				show ? $(this).hide() : $(this).show();
			}
		});

	}


	return {

		umlHeight: 500,

		notAdd: true,

		addEntity: function (model, idObj, successFun) {
			if (pdm.notAdd) {
				successFun();
				return;
			}

			function getParams(model) {
				var params = {};
				params.createAccountId = getCurAccountId();
				params.modifyAccountId = getCurAccountId();
				params.type = 1; 	//1、表，2、视图
				params.moduleId = idObj.moduleId;
				params.projectId = idObj.projectId;
				params.name = model.name;
				params.nameCn = model.name;
				params.engine = 1; //1:InnoDB; 2:MyISAM
				params.remark = '';
				params.script = '';
				params.xPosition = model.position.x;
				params.yPosition = model.position.y;
				params.versionId = -1;
				return params;

			}

			slog.log('添加实体----------------------');
			slog.log(model);
			var params = getParams(model);

			var url = action + 'entity/';
			sPost.ajax(url, params, function (data) {
				if (sUtils.isSucObj(data)) {
					model.id = data.obj.id;
					successFun();
				}
			});
		},

		/**
		 * 部署/实施
		 */
		deploy: function () {

		},

		/**
		 * 加载zTree
		 *
		 * @param $tree ztree对象
		 */
		loadTree: function ($tree) {

			var url = action + 'project/';
			url = action + 'accountManage/getAccountProject';
			var iconUrl = path + '/resources/plugins/zTree/css/zTreeStyle/img/diy/';
			var params = {id: accountId};
			slog.log(accountId);
			slog.log(params);
			slog.log(url);
			sPost.ajax(url, params, function (data, textStatus, jqXHR) {
				//slog.log(data.obj);
				var projectData = data.obj;

				var children1 = {
					id: (count++), type: 'versionRoot',
					pId: 0, isParent: true,
					projectId: 0,
					name: '版本', icon: iconUrl + '6.png'
				};
				var children2 = {
					id: (count++), type: 'moduleRoot',
					pId: 0, isParent: true,
					projectId: 0,
					name: '模块', icon: iconUrl + '2.png'
				};
				$.each(projectData, function (i, val) {
					val.isParent = true;
					val.projectId = val.id;
					val.type = 'project';
					if (val['projectAuto'] == 1) { //读写权限
						val.icon = iconUrl + '3.png';
					}

					children1.pId = val.id;
					children1.projectId = val.id;
					children2.pId = val.id;
					children2.projectId = val.id;
					projectData.push($.extend({}, children1));
					projectData.push($.extend({}, children2));
				});
				slog.log(projectData);
				$tree.addNodes(null, projectData);
			});

		},
		/**
		 * zTree 加载配置
		 */
		setting: {
			data: {
				simpleData: {
					enable: true
				}
			},
			/*			async: { // 动态加载子节点 TODO
			 enable: true,
			 dataType: "json",
			 autoParam: ["projectId"],
			 url: "js/data/find-chart-by-project.json",
			 dataFilter: function (treeId, parentNode, responseData) {
			 debugger;
			 var chartData = responseData.obj;
			 slog.log(chartData);
			 $.each(chartData, function (i, chart) {
			 chart.projectId = parentNode.id;
			 chart.isParent = true;
			 chart.type = "module";
			 chart.icon = "images/uml/uml_chart.png";
			 });
			 return chartData;
			 }
			 },*/
			callback: {
				onExpand: function (event, treeId, treeNode) {
					slog.log(treeNode);
					var type = treeNode.type;
					var url = 'js/data/find-chart-by-project.json';
					if (type == 'moduleRoot' || type == 'version') {

						//添加测试数据模块
						/*sPost.ajax(url, {}, function (data) {
						 if (data.success) {
						 var modules = data.obj;
						 var newNodes = [];
						 $.each(modules, function (i, module) {
						 module.projectId = treeNode.id;
						 module.isParent = true;
						 module.type = 'module';
						 module.icon = 'images/uml/uml_chart.png';
						 newNodes.push(module);
						 });
						 $.fn.zTree.getZTreeObj(treeId).addNodes(treeNode, newNodes);
						 } else {
						 slog.error('查询失败' + data.msg);
						 }
						 });
						 */
						/*						url = action + 'pdm/getChart';
						 sPost.ajax(url, {moduleId: 1}, function (data) {
						 if (data.success) {
						 var module = data.obj;
						 slog.log(module);
						 slog.log(module.domainShapeInfo);
						 module.projectId = treeNode.id;
						 module.isParent = true;
						 module.type = 'module';
						 module.icon = 'images/uml/uml_chart.png';
						 $.fn.zTree.getZTreeObj(treeId).addNodes(treeNode, module);
						 } else {
						 slog.error('查询失败' + data.msg);
						 }
						 });*/
						var versionId = DEFAULT_VERSION_ID;
						if (type == 'version') {
							versionId = treeNode.id;
						}

						url = action + 'module/';
						sPost.ajaxFind(url, {
							'Q_projectId_=_long': treeNode.projectId,
							'Q_versionId_=_Long': versionId
						}, function (data) {
							if (data.success) {
								slog.log(data.obj);
								var modules = data.obj;
								var newNodes = [];
								$.each(modules, function (i, module) {
									module.projectId = treeNode.pId;
									module.pId = module.parentId;
									module.isParent = true;
									module.type = 'module';
									module.icon = 'images/uml/uml_chart.png';
									newNodes.push(module);
								});
								$.fn.zTree.getZTreeObj(treeId).addNodes(treeNode, newNodes);
							} else {
								slog.error('查询失败' + data.msg);
							}
						});

					}
					else if (type == 'versionRoot') {
						slog.log('展开版本，查看版本信息');
						url = action + 'version/';
						sPost.ajaxFind(url, {'Q_projectId_=_long': treeNode.pId}, function (data) {

							if (data.success) {
								var modules = data.obj;
								var newNodes = [];
								$.each(modules, function (i, module) {
									module.projectId = treeNode.pId;
									module.isParent = true;
									module.type = 'version';
									module.icon = 'images/uml/uml_chart.png';
									newNodes.push(module);
								});
								$.fn.zTree.getZTreeObj(treeId).addNodes(treeNode, newNodes);
							} else {
								slog.error('查询失败' + data.msg);
							}
						});
					} else if (type == 'module') {
						slog.log('展开模块，查看表');
						url = action + 'entity/';

						sPost.ajaxFind(url, {
							'Q_moduleId_=_long': treeNode.id,
							'Q_versionId_=_Long': treeNode.versionId
						}, function (data) {
							if (data.success) {
								var modules = data.obj;
								var newNodes = [];
								$.each(modules, function (i, module) {
									module.projectId = treeNode.pId;
									module.isParent = false;
									module.type = 'table';
									module.icon = 'images/uml/uml_chart.png';
									newNodes.push(module);
								});
								$.fn.zTree.getZTreeObj(treeId).addNodes(treeNode, newNodes);
							} else {
								slog.log('Find Table Error: ' + data.msg);
							}
						});
					}
				},
				beforeExpand: function (treeId, treeNode) {
					var type = treeNode.type;
					if (type != 'project') {
						$.fn.zTree.getZTreeObj(treeId).removeChildNodes(treeNode);
						treeNode['isParent'] = true;
					}
				},
				beforeAsync: function (treeId, treeNode) { // TODO
					//if (treeNode && (treeNode.type == 'moduleRoot'
					//				|| treeNode.type == 'versionRoot'
					//				|| treeNode.type == 'module')) {
					//	return true;
					//} else {
					//	return false;
					//}
				},
				onDblClick: function (event, treeId, nodeData) {
					slog.log('dblClick~~~~~~~~~~~~');
					if (nodeData == null) return;
					var type = nodeData.type;
					if (type == 'table') {
						slog.log('table dblClick');
						pdmOpenWin.openWinEditEntity(nodeData);
					}
				},
				//TODO:点击旧版本模块时，隐藏工具栏
				onClick: function (event, treeId, nodeData) {
					slog.log(nodeData);
					if (nodeData.type == 'project') {
						/*点击项目时显示添加版本按钮*/

						showLeftBtn('openWinAddVersion', true);

					} else if (nodeData.type == 'module') {
						/*点击模块时出现添加子模块，编辑、删除模块*/
						var tabClass = 'tab_' + nodeData.id;
						if (mainTab.isExistTab(nodeData.id)) {
							mainTab.active('.' + tabClass);
						} else {
							var url = action + 'pdm/getChart';
							sPost.ajax(url, {
								'moduleId': nodeData.id,
								'versionId': nodeData.versionId
							}, function (data) {
								mainTab.addTab({
									title: nodeData.name + nodeData.id,
									afterAdd: function (tab, panel) {
										tab.addClass(tabClass);
										$.get('pages/template.html').done(function (htmlData) {
											panel.html(htmlData);
											nodeData = $.extend({}, data.obj, nodeData);

											/*将project和chart缓存在工具栏上，以待后续操作用到*/
											panel.find('.tools_bar:first').data('project', nodeData.getParentNode());
											panel.find('.tools_bar:first').data('chart', nodeData);

											panel.find('#canvas').umlCanvas(nodeData);
											panel.height(pdm.umlHeight);
											panel.find('.uml_easel').height(pdm.umlHeight);

											if (nodeData.versionId != DEFAULT_VERSION_ID) {
												panel.find('.tools_bar').hide();
												panel.find('.uml_tools').hide();
											}
										});
									},
									closeable: true
								});
							});
						}
						if (nodeData.versionId == DEFAULT_VERSION_ID) {
							showLeftBtn('openWinAddVersion', false);
						} else {
							$('.panel-heading').find('button').hide();
						}
					} else if (nodeData.type == 'version') {
						/*点击版本的时候，隐藏所有按钮*/
						$('.panel-heading').find('button').hide();

					} else if (nodeData.type == 'table') {
						/*点击表格时，隐藏所有按钮*/
						$('.panel-heading').find('button').hide();

					} else if (nodeData.type == 'versionRoot') {
						/*点击版本根目录时，隐藏所有按钮*/
						$('.panel-heading').find('button').hide();

					} else if (nodeData.type == 'moduleRoot') {
						/*点击模块根目录时，出现添加子模块，不需要编辑、删除按钮*/
						$('.panel-heading').find('button').hide();
						$('#openWinAddModule').show();
						//展开模块
					}
				}

			}
		},

		/**
		 *    删除实体
		 * @param entityId
		 */
		deleteEntity: function (entityId) {
			slog.log('删除实体, ID: ' + entityId);

			var url = action + 'entity/' + entityId;

			sPost.ajaxDel(url, null, function (data) {
				if (data.success) {
					slog.log('删除实体成功');
					layer.alert("删除成功", {icon: 1, title: '提示'});
				} else {
					slog.log('删除实体失败');
				}
			});
		},

		/**
		 * 删除实体关系
		 * @param lines 数组【关系对象】
		 */
		deleteEntityReletesByArr: function (lines) {
			var arrIds = [];
			$.each(lines, function (i, line) {
				arrIds.push(line.id);
			});
			pdm.deleteEntityReletes(arrIds.join(','));
		},

		/**
		 *    删除实体关系
		 * @param ids
		 */
		deleteEntityReletes: function (ids) {
			slog.log('删除多条实体关系: ' + ids);

			if (sUtils.isNull(ids)) {
				return;
			}
			var url = action + 'entityRelate/batch';

			sPost.ajax(url, {"ids": ids}, function (data) {
				if (data.success) {
					slog.log('删除多条实体关系成功');
				} else {
					slog.log('删除多条实体关系失败');
				}
			});
		},

		/**
		 * 新增或修改模块
		 *
		 * @param project zTree点击的结点
		 * @param $tree
		 * @param isAdd 是否为新增
		 */
		saveOrEditModule: function (project, $tree, isAdd, dbConnInfoData, databaseData) {

			var url = action + 'module/';
			var module = sUtils.getFormParams(moduleAddOrEditFormSelector);
			var result = false;

			function getModule(project, module) {
				var params = {};
				params.id = '';
				params.name = module.name;
				params.remark = module.remark;
				params.projectId = project.projectId;
				params.parentId = -1;
				params.createAccountId = getCurAccountId();
				params.accountId = getCurAccountId();
				params.databaseId = databaseData.id;
				params.dbInfoId = dbConnInfoData.id;
				params.pathUrl = '';
				params.shorIndex = 1;//排序默认为1
				params.versionId = DEFAULT_VERSION_ID;//新增的数据版本默认为-1
				return params;
			}

			if ($(moduleAddOrEditFormSelector).valid()) {
				result = true;

				if (isAdd) {
					var params = getModule(project, module);
					slog.log(params);
					sPost.ajax(url, params, function (data) {
						if (data.success) {
							//保存成功后，需要往ztree中添加节点
							$tree.addNodes($tree.getSelectedNodes()[0], [{
								name: data.obj.name,
								id: data.obj.id, //ajax返回数据才有id
								isParent: true,
								type: 'module',
								projectId: project.projectId,
								versionId: data.obj.versionId,
								icon: 'images/uml/uml_chart.png'
							}]);
							layer.alert("新增模块成功", {icon: 1, title: '提示'});
						} else {
							layer.alert("新增模块失败" + data.msg, {icon: 5, title: '提示'});
							result = false;
						}
					});
				} else {
					var params = sUtils.getFormParams(moduleAddOrEditFormSelector);
					params.accountId = getCurAccountId();
					params.modifyAccountId = getCurAccountId();
					params.databaseId = databaseData.id;
					params.dbInfoId = dbConnInfoData.id;

					sPost.ajaxPut(url, params, function (data) {
						if (data.success) {
							//修改成功之后，更新要保存在z-tree节点上
							data = $tree.getSelectedNodes()[0];
							data.name = params.name;
							data.databaseId = params.databaseId;
							data.dbInfoId = params.dbInfoId;
							$tree.updateNode(data);
							layer.alert("修改模块成功", {icon: 1, title: '提示'});
						} else {
							layer.alert("修改模块失败" + data.msg, {icon: 5, title: '提示'});
							result = false;
						}
					});
				}
			}
			return result;

		},


		/**
		 * 删除模块
		 * @param project
		 */
		delModule: function (project, $tree) {

			if (sUtils.isNull(project) || project.type != 'module') {
				layer.alert('请选择要删除的模块！', {icon: 5, title: '提示'});
				return;
			}
			layer.confirm('确定要删除模块 "' + project.name + ' "吗？', {icon: 3, title: '提示'}, function (index) {

				var url = action + 'module/' + project.id;

				slog.log(url);

				sPost.ajaxDel(url, {}, function (data) {
					if (data.success) {
						slog.log("Delete Method 成功！");
						slog.log(data);

						layer.alert('删除成功！', {icon: 1, title: '提示'});
						$tree.removeNode($tree.getNodeByTId(project.tId));

						$('.tab_' + project.id).remove();
						mainTab.active('#tab_index');

					} else {
						slog.error("Delete Method Error : " + data.msg);
						layer.alert('删除失败！', {icon: 5, title: '提示'});
					}
				});

				layer.close(index);
			});
		},

		/**
		 *  保存版本
		 */
		saveVersion: function (project, $tree) {
			var url = action + 'version/ ';
			var result = false;

			if ($(versionAddFormSelector).valid()) {
				result = true;
				var params = sUtils.getFormParams(versionAddFormSelector);
				params.projectId = project.id;
				params.accountId = getCurAccountId();
				sPost.ajax(url, params, function (data) {
					if (data.success) {
						layer.alert('新增成功！', {icon: 1, title: '提示'});
					} else {
						layer.alert('新增失败！' + data.msg, {icon: 5, title: '提示'});
						result = false;
					}
				});
			}
			return result;
		},

		/**
		 * 加载实体数据和字段数据
		 */
		loadEntityAndField: function (nodeData) {

			var versionId = DEFAULT_VERSION_ID;

			var url = action + 'entity/' + nodeData.id;
			sPost.ajaxGet(url, function (data) {
				if (data.success) {
					slog.log('查找实体成功');
					slog.log(data.obj);
					$('#entityScript').val(data.obj.script);
					sUtils.setFrom(entityAddOrEditFormSelector, data.obj);
					versionId = data.obj.versionId;
				} else {
					slog.log('查找失败');
				}
			});
			var fieldList = [];
			url = action + 'field/';
			sPost.ajaxFind(url, {
				'Q_entityId_=_Long': nodeData.id,
				'Q_versionId_=_Long': versionId
			}, function (data) {
				if (data.success) {
					slog.log('查找字段成功');
					slog.log(data.obj);
					fieldList = data.obj;
					if (sUtils.notNull(fieldList)) {
						sUtils.transactionEnum(fieldList, enums, enumMap);
						slog.log(fieldList);
					}
				} else {
					slog.log('查找失败');
				}
			});

			return fieldList;
		},

		/**
		 * 编辑实体
		 */
		editEntity: function (nodeData) {

			var url = action + 'entity/';
			var result = false;
			if ($(entityAddOrEditFormSelector).valid()) {
				result = true;
				var params = sUtils.getFormParams(entityAddOrEditFormSelector);
				var script = $('#entityScript').val();
				params.script = script;
				params.modifyAccountId = getCurAccountId();

				sPost.ajaxPut(url, params, function (data) {
					if (data.success) {
						slog.log('修改实体成功');
						slog.log(data);
						layer.alert("修改实体成功", {icon: 1, title: '提示'});
						nodeData.name = params.nameCn;
						$("#" + nodeData.id).find(".name").html(params.nameCn);

						//删除实体所有属性后，在添加现有的字段属性
						$('#' + nodeData.id).find(".properties").html('');
						$.each(nodeData.properties, function (idx, val) {
							nodeData.properties.remove(1);
						});

						var fields = $(addOrEditFieldJqgridTableSelector).jqGrid("getRowData");
						var property = null;

						$.each(fields, function (i, val) {
							property = new Property(val.nameCn, val.type);
							addProperty(nodeData, property, true);
						});
					} else {
						layer.alert("修改实体失败!" + data.msg, {icon: 5, title: '提示'});
						result = false;
					}
				});
			}
			return result;
		},

		/**
		 * 新增字段
		 * @param nodeData
		 */
		saveField: function (nodeData) {

			slog.log('新增字段');

			var dataParams;
			var url = action + 'field/';

			function getField(entityId) {
				var params = {};
				var formData = sUtils.getFormParams(entityAddOrEditFormSelector);
				slog.log(formData);
				var fields = $(addOrEditFieldJqgridTableSelector).jqGrid("getRowData");
				var length = fields.length;
				var lastSort = 0;
				if (sUtils.notNull(fields)) {
					lastSort = fields[length - 1].sortIndex;
				}

				params.createAccountId = getCurAccountId();
				params.nameCn = '字段' + (length + 1);
				params.name = 'field' + (length + 1);
				params.type = '8';
				params.isNull = 1;
				params.isPmKey = 2;
				params.autoIncrement = 2;
				params.length = 0;
				params.decimalPoint = 0;
				params.entityId = entityId;
				params.script = '';
				params.remark = '';
				params.sortIndex = parseInt(lastSort) + 1;
				params.versionId = DEFAULT_VERSION_ID;
				params.moduleId = formData.moduleId;
				params.projectId = formData.projectId;

				return params;
			}

			dataParams = getField(nodeData.id);

			sPost.ajax(url, dataParams, function (data) {
				if (data.success) {
					slog.log('新增成功');
					dataParams = data.obj;
					slog.log(dataParams.id);
				} else {
					slog.log('新增失败');
				}
			});

			var arr = [];
			arr.push(dataParams);
			sUtils.transactionEnum(arr, enums, enumMap);

			$(addOrEditFieldJqgridTableSelector).jqGrid('addRowData', arr[0].id, arr[0], 'last');

			var property = new Property(arr[0].nameCn, arr[0].type);
			addProperty(nodeData, property, false);
		},

		/**
		 * 插入模板字段
		 * 现模板为插入(编号 英文名 中文名 创建时间 修改时间 创建人 修改人 备注)
		 * @param nodeData
		 */
		insertTemplateField: function (nodeData) {

			slog.log('插入模板');
		},
		/**
		 * 复制字段
		 */
		copyField: function (nodeData) {

			var url = action + 'field/';
			var paramsArr = [];
			var params;
			// 获取字段表格选中行
			var selectedIds = $(addOrEditFieldJqgridTableSelector).jqGrid("getGridParam", "selarrrow");
			slog.log(selectedIds);
			// 判断是否选中
			if (sUtils.isNull(selectedIds)) {
				layer.alert('请选择要复制的字段！', {icon: 5, title: '提示'});
				return;
			}
			var isNullData = pdm.getTrDatas(enumMap, 'pdm_field-isNull', false);
			var isPmKeyData = pdm.getTrDatas(enumMap, 'pdm_field-isPmKey', false);
			var autoIncrementData = pdm.getTrDatas(enumMap, 'pdm_field-autoIncrement', false);
			var typeData = pdm.getTrDatas(enumMap, 'pdm_field-type', false);
			slog.log(typeData);

			$.each(selectedIds, function (idx, val) {
				params = $(addOrEditFieldJqgridTableSelector).jqGrid("getRowData", val);
				params.id = '';
				params.name = params.name + '_copy';
				params.nameCn = params.nameCn + '_副本';
				params.isNull = isNullData[params.isNull];
				params.isPmKey = isPmKeyData[params.isPmKey];
				params.autoIncrement = autoIncrementData[params.autoIncrement];
				params.type = typeData[params.type];

				sPost.ajax(url, params, function (data) {
					if (data.success) {
						slog.log('复制字段成功');
						slog.log(data);
						params = data.obj;
						paramsArr.push(params);
					} else {
						slog.error('复制字段失败' + params);
					}
				});
			});

			sUtils.transactionEnum(paramsArr, enums, enumMap);
			$.each(paramsArr, function (idx, params) {
				slog.log(params);
				$(addOrEditFieldJqgridTableSelector).jqGrid('addRowData', params.id, params, 'last');
			});

			$.each(paramsArr, function (idx, val) {
				var property = new Property(val.nameCn, val.type);
				addProperty(nodeData, property, false);
			})
		},

		/**
		 * 删除所选字段
		 * 若删除的字段为主键，则在索引表删除对应的索引字段
		 */
		delField: function (nodeData) {

			// 获取字段表格选中行
			var selectedIds = $(addOrEditFieldJqgridTableSelector).jqGrid("getGridParam", "selarrrow");
			slog.log(selectedIds);
			// 判断是否选中
			if (sUtils.isNull(selectedIds)) {
				layer.alert('请选择要删除的字段！', {icon: 5, title: '提示'});
				return;
			}

			var fieldIds = selectedIds.join(",");

			slog.log(fieldIds);

			layer.confirm('确定要删除吗？', {icon: 3, title: '提示'}, function (index) {

				var url = action + 'field/batch';

				sPost.ajax(url, {'ids': fieldIds}, function (data) {
					if (data.success) {
						slog.log("Delete Method 成功！");
						slog.log(data);

						/*
						 selectedIds个数会动态减少，故每次只删除数组的第一个元素，直到数组个数为0
						 */
						while (selectedIds.length) {
							var params = $(addOrEditFieldJqgridTableSelector).jqGrid('getRowData', selectedIds[0]);
							if (params.isPmKey == '是') {
								url = action + 'indexInfo/deleteIndexByFieldId/' + params.id;
								sPost.ajaxDel(url, {}, function (data) {
									if (data.success) {
										slog.log(data);
									} else {
										slog.error("索引删除失败：" + data.msg);
									}
								});
							}
							$(addOrEditFieldJqgridTableSelector).jqGrid("delRowData", selectedIds[0]);
						}
						layer.alert('删除成功！', {icon: 1, title: '提示'});

						//删除实体所有属性后，在添加现有的字段属性
						$('#' + nodeData.id).find(".properties").html('');
						$.each(nodeData.properties, function (idx, val) {
							nodeData.properties.remove(1);
						});

						var fields = $(addOrEditFieldJqgridTableSelector).jqGrid("getRowData");
						var property = null;

						$.each(fields, function (i, val) {
							property = new Property(val.nameCn, val.type);
							addProperty(nodeData, property, true);
						});
						slog.log(fields);
					} else {
						slog.error("Delete Method Error : " + data.msg);
						layer.alert('删除失败！', {icon: 5, title: '提示'});
					}
				});
				layer.close(index);
			});
		},

		saveFieldSort: function () {
			slog.log('保存字段顺序');
			var fieldIdArr = [];

			var tableData = $(addOrEditFieldJqgridTableSelector).jqGrid("getRowData");
			$.each(tableData, function (idx, val) {
				slog.log(val);
				fieldIdArr.push(val.id);
			});

			var fieldIds = fieldIdArr.join(',');
			slog.log(fieldIds);

			if (sUtils.isNull(fieldIds)) {
				return;
			}

			var url = action + 'field/saveFieldSort';
			sPost.ajax(url, {"ids": fieldIds}, function (data) {
				if (data.success) {
					slog.log('保存顺序成功');
					layer.alert("保存顺序成功", {'icon': 1, 'title': '提示'});
				} else {
					slog.log('保存顺序失败');
				}
			});
		},

		editEntityRelate: function () {

			var url = action + 'entityRelate/';
			var result = false;

			if ($(relAddOrEditModelFormSelector).valid()) {
				result = true;
				var params = sUtils.getFormParams(relAddOrEditModelFormSelector);
				var field1 = $('#field1').val();
				var field2 = $('#field2').val();
				params.startFieldId = field1;
				params.endFieldId = field2;
				params.modifyAccountId = getCurAccountId();

				sPost.ajaxPut(url, params, function (data) {
					if (data.success) {
						layer.alert("修改关系成功", {icon: 1, title: '提示'});
					} else {
						layer.alert("修改关系失败" + data.msg, {icon: 5, title: '提示'});
						result = false;
					}
				});
			}
			return result;
		},

		/**
		 *
		 * @param line
		 * @param idObj
		 * @param successFun
		 */
		addRelate: function (line, idObj, successFun) {
			function getLineParams(line) {
				var tmp = {};
				var name = 'rel_' + line.id.substr(0, 4);
				tmp.name = name;
				tmp.nameCn = name;
				tmp.startObjectId = line.fromShapeId;
				tmp.endObjectId = line.toShapeId;
				tmp.multiplicity = JSON.stringify(line.multiplicity);
				//tmp.aFieldId = null;
				//tmp.bFieldId = null;
				tmp.createAccountId = getCurAccountId();
				tmp.modifyAccountId = getCurAccountId();
				tmp.moduleId = idObj.moduleId;
				tmp.versionId = DEFAULT_VERSION_ID;
				return tmp;
			}

			var url = action + 'entityRelate/';
			var params = getLineParams(line);

			sPost.ajax(url, params, function (data) {
				if (sUtils.isSucObj(data)) {
					line.id = data.obj.id;
					slog.log('实体关系入库成功，更新id');
					slog.log(line);
				}
				successFun();
			});
		},

		updateRelate: function (line) {
			var url = action + 'entityRelate/points';
			var params = {
				id: line.id,
				multiplicityJson: JSON.stringify(line.multiplicity),
				points: line.points
			};
			slog.log('更新实体关系坐标数据: ' + params);
			slog.log(params);
			sPost.ajax(url, params, function (data) {
				slog.log('更新实体关系坐标数据结果: ' + data.success);
			});
		},

		loadDatabase: function () {
			slog.log("查找数据库");

			var params = sUtils.getFormParams(databaseSearchFormSeletor);
			slog.log(params);

			var url = action + "database/findDatabase";
			sPost.ajaxFind(url, params, function (data) {
				if (data.success) {
					slog.log("Find Method 成功！");
					params = data.obj;
					slog.log(params);

					sUtils.transactionEnum(params, enums, enumMap);

					$(databaseTableSeletor).clearGridData();
					if (params != null) {
						$(databaseTableSeletor).setGridParam({data: params});
					}
					$(databaseTableSeletor).trigger("reloadGrid");
				} else {
					slog.error("find Method Error : " + data.msg);
				}
			});
		},

		/**
		 * 生成代码
		 * @param objId
		 * @param type
		 */
		createCode: function (objId, type) {
			slog.log('createCode');
			if (type == 'projectId') {

			} else if (type == 'moduleId') {


			}

		},

		/**
		 * 保存图形坐标
		 * @param data
		 */
		saveCoordinates: function (canvas) {
			layer.load(1, {shade: [0.8, '#393D49'], time: 3000})
			//从data中解析出对象和坐标，进行数据保存
			slog.log('保存图形中对象的坐标数据')
			slog.log(canvas);
			var relates = [];
			var entitys = []
			var relate = {};
			var entity = {};
			$.each(canvas.LINES, function (key, value) {
				relate = {};
				relate.id = value.id;
				relate.multiplicityJson = JSON.stringify(value.multiplicity);
				relate.points = value.points;
				relates.push(relate);
			});

			$.each(canvas.MODELS, function (key, value) {
				entity = {};
				entity.id = value.id;
				entity.xPosition = value.position.x;
				entity.yPosition = value.position.y;
				entitys.push(entity);
			});
			slog.log(entitys);
			slog.log(relates);
			var url = action + 'pdm/updateChart';
			var params = {
				jsonEntitys: JSON.stringify(entitys),
				jsonRelates: JSON.stringify(relates)
			};
			slog.log('请求url和参数');
			slog.log(url);
			slog.log(params);
			//FIXME 需要添加waitbar

			sPost.ajax(url, params);
			layer.closeAll('loading');
		},

		/**
		 * 把枚举值翻译成jqgrid col使用的editoptions
		 * @param enumMap
		 * @param key
		 * @returns {string}
		 */
		getEditoptions: function (enumMap, key) {
			var arr = enumMap.get(key);
			var es = [];
			$.each(arr, function (i, val) {
				es.push(val.enumCode + ':' + val.enumValue);
			});
			return es.join(';');
		},

		/**
		 * 获取翻译和翻译反转的枚举对象
		 * @param enumMap
		 * @param key
		 * @param flag
		 * @returns {{}}
		 */
		getTrDatas: function (enumMap, key, flag) {
			var arr = enumMap.get(key);
			var es = {};
			$.each(arr, function (i, val) {
				if (flag) {
					es[val.enumCode] = val.enumValue;
				} else {
					es[val.enumValue] = val.enumCode;
				}
			});
			return es;
		},

		test: function () {
			slog.log('pdm.test path: ' + path);
		}
	}

}();